
const bcrypt = require('bcryptjs')

const db = require('../db/index.js')
const { isValidPassword, isValidNickname } = require('./verify.js')


// 获取用户信息
const getUserInfo = async (req, res) => {
    try {
        const sqlStr = 'select uid,username,nickname,avatar_path,status from users where uid=?'
        const [results] = await db.query(sqlStr, [req.user.uid])
        if (results.length <= 0 || !results[0].status) {
            return res.cc('用户不存在', 40)
        }
        if (results.length !== 1) {
            return res.cc('数据读取失败', 30)
        }
        return res.send({
            code: 0,
            msg: '获取用户信息成功',
            data: results[0]
        })
    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: getUserInfo-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

// 设置用户昵称
const updateNickname = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.newNickname) {
        return res.cc('新昵称不能为空', 10)
    }
    const newNickname = req.body.newNickname
    if (!isValidNickname(newNickname)) {
        return res.cc('昵称不合法', 1)
    }
    try {
        // 检查用户信息
        let sqlStr = 'select uid,nickname,status from users where uid=?'
        let [results] = await db.query(sqlStr, [req.user.uid])
        if (results.length <= 0 || !results[0].status) {
            return res.cc('用户不存在', 40)
        }
        if (results.length !== 1) {
            return res.cc('用户数据读取失败', 30)
        }
        // 更新数据库
        sqlStr = 'update users set nickname=? where uid=?'
            ;[results] = await db.query(sqlStr, [newNickname, req.user.uid])
        if (results.affectedRows !== 1) {
            return res.cc('更新失败', 30)
        }
        return res.send({
            code: 0,
            msg: '更新用户信息成功',
            data: {
                uid: req.user.uid,
                username: req.user.username,
                nickname: newNickname,
            }
        })

    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: updateNickname-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

// 更新密码
const updatePassword = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    let { oldPassword, newPassword } = req.body
    if (!isValidPassword(newPassword)) {
        return res.cc('新密码不合法', 1)
    }
    try {
        // 检查用户和密码
        let sqlStr = 'select uid,password,status from users where uid=?'
        let [results] = await db.query(sqlStr, [req.user.uid])
        if (results.length !== 1) {
            return res.cc('用户数据读取失败', 30)
        }
        if (results[0].status !== 1) {
            return res.cc('用户不存在', 40)
        }
        if (!bcrypt.compareSync(oldPassword, results[0].password)) {
            return res.cc('密码错误, 更新失败', 2)
        }
        // 加密新密码
        newPassword = bcrypt.hashSync(newPassword, 10)
        // 更新数据库
        sqlStr = 'update users set password=? where uid=?'
            ;[results] = await db.query(sqlStr, [newPassword, req.user.uid])
        if (results.affectedRows !== 1) {
            return res.cc('密码更新失败', 30)
        }
        return res.send({
            code: 0,
            msg: '更新用户密码成功',
            data: {
                uid: req.user.uid
            }
        })

    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: updatePassword-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

// 根据信息查询用户
const searchKeyword = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.keyword) {
        return res.cc('查询关键词不能为空', 10)
    }
    const keyword = req.body.keyword
    const keywordNum = parseInt(keyword)
    const resList = []
    try {
        if (keywordNum) {
            const sqlStr = 'select uid,username,status from users where uid=?'
            const [results] = await db.query(sqlStr, [keywordNum])
            if (results.length > 0) {
                resList.push(results[0].uid)
            }
        }


        const sqlStr = 'select uid,username,status from users where username like ? or nickname like ?'
        const [results] = await db.query(sqlStr, [`%${keyword}%`, `%${keyword}%`])
        results.forEach(u => {
            if (u.status === 1) {
                resList.push(u.uid)
            }
        })
        return res.send({
            code: 0,
            msg: '查询用户成功',
            data: {
                uid: req.user.uid,
                keyword: keyword,
                users: resList
            }
        })

    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: searchKeyword-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

// 根据uid获取用户基本信息
const getInfoByUid = async (req, res) => {
    if (!req.body) {
        return res.cc('请求体不能为空', 10)
    }
    if (!req.body.uid) {
        return res.cc('查询uid不能为空', 10)
    }
    try {
        const sqlStr = 'select uid,username,nickname,avatar_path,status from users where uid=?'
        const [results] = await db.query(sqlStr, [req.body.uid])
        if (results.length === 0 || results[0].status !== 1) {
            return res.cc('目标用户不存在', 1)
        }
        return res.send({
            code: 0,
            msg: '获取用户基本信息成功',
            data: results[0]
        })

    } catch (err) {
        if (db.isDatabaseError(err)) {
            console.log('Error: getInfoByUid-> ', err.message)
            return res.cc(err, 30)
        } else {
            throw err
        }
    }
}

module.exports = {
    getUserInfo,
    updateNickname,
    updatePassword,
    searchKeyword,
    getInfoByUid
}